package servlet;

import model.DBUtil;
import model.Guser;
import model.Puser;
import model.Ruser;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.MessageDigest;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/new-login")
public class NewLonin  extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        Integer role = Integer.valueOf(req.getParameter("role"));
        String phone = req.getParameter("phone");
        String password = req.getParameter("password");
        PrintWriter out = resp.getWriter();
        if(role==1){
        try {
            // 2. 通过 MySQL 查询，得到用户对象
            Puser puser = query1(phone, password);
            if (puser == null) {
                // 查不到对应的用户，代表用户名密码错误
                out.print("<script language='javascript'>alert('Wrong password. Login again!!');window.location.href='/new-login.html';</script>");
                return;
            }
            HttpSession session = req.getSession();
            session.setAttribute("pcurrentUser", puser);
            resp.sendRedirect("/");
        } catch (SQLException exc) {
            throw new ServletException(exc);
        }
    }
        if(role==2){
            try {
                // 2. 通过 MySQL 查询，得到用户对象
                Ruser ruser = query2(phone, password);
                if (ruser == null) {
                    // 查不到对应的用户，代表用户名密码错误
                    out.print("<script language='javascript'>alert('Wrong password. Login again!!');window.location.href='/new-login.html';</script>");
                    return;
                }
                HttpSession session = req.getSession();
                session.setAttribute("rcurrentUser", ruser);
                resp.sendRedirect("/");
            } catch (SQLException exc) {
                throw new ServletException(exc);
            }
        }
        if(role==3){
            try {
                // 2. 通过 MySQL 查询，得到用户对象
                Guser guser = query3(phone, password);
                if (guser == null) {
                    // 查不到对应的用户，代表用户名密码错误
                    out.print("<script language='javascript'>alert('Wrong password. Login again!!');window.location.href='/new-login.html';</script>");
                    return;
                }
                HttpSession session = req.getSession();
                session.setAttribute("gcurrentUser", guser);
                resp.sendRedirect("/");
            } catch (SQLException exc) {
                throw new ServletException(exc);
            }
        }
    }
    private Puser query1(String phone, String password) throws SQLException {
        password = hash(password);
        try (Connection c = DBUtil.getConnection()) {
            String sql = "SELECT puid,pusername,phone FROM puser WHERE phone = ? AND ppassword = ?";
            try (PreparedStatement s = c.prepareStatement(sql)) {
                s.setString(1, phone);
                s.setString(2, password);

                try (ResultSet rs = s.executeQuery()) {
                    if (!rs.next()) {
                        return null;
                    }

                    Puser user = new Puser();
                    user.puid = rs.getInt("puid");
                    user.phone = rs.getString("phone");
                    user.pusername = rs.getString("pusername");

                    return user;
                }
            }

        }
    }
    private Ruser query2(String phone, String password) throws SQLException {
        password = hash(password);
        try (Connection c = DBUtil.getConnection()) {
            String sql = "SELECT ruid,rname,rphone FROM ruser WHERE rphone = ? AND rpassword = ?";
            try (PreparedStatement s = c.prepareStatement(sql)) {
                s.setString(1, phone);
                s.setString(2, password);

                try (ResultSet rs = s.executeQuery()) {
                    if (!rs.next()) {
                        return null;
                    }

                    Ruser user = new Ruser();
                    user.ruid = rs.getInt("ruid");
                    user.rphone = rs.getString("rphone");
                    user.rname = rs.getString("rname");

                    return user;
                }
            }

        }
    }
    private Guser query3(String phone, String password) throws SQLException {
        try (Connection c = DBUtil.getConnection()) {
            String sql = "SELECT guid,gphone FROM guser WHERE gphone = ? AND gpassword = ?";
            try (PreparedStatement s = c.prepareStatement(sql)) {
                s.setString(1, phone);
                s.setString(2, password);

                try (ResultSet rs = s.executeQuery()) {
                    if (!rs.next()) {
                        return null;
                    }

                    Guser guser = new Guser();
                    guser.guid = rs.getInt("guid");
                    guser.gphone = rs.getString("gphone");


                    return guser;
                }
            }

        }
    }
    private String hash(String password) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");

            byte[] bytes = password.getBytes("UTF-8");
            byte[] digest = messageDigest.digest(bytes);
            StringBuilder sb = new StringBuilder();
            for (byte b : digest) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();

        }  catch (Exception exc) {
            return password;
        }
    }
}


